package com.cykj.pos.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cykj.common.annotation.DataSource;
import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.core.domain.entity.SysDept;
import com.cykj.common.core.domain.entity.SysUser;
import com.cykj.common.core.domain.model.LoginUser;
import com.cykj.common.enums.DataSourceType;
import com.cykj.common.utils.SecurityUtils;
import com.cykj.common.utils.ServletUtils;
import com.cykj.common.utils.spring.SpringUtils;
import com.cykj.framework.web.service.TokenService;
import com.cykj.pos.domain.*;
import com.cykj.pos.domain.dto.*;
import com.cykj.pos.domain.vo.BizTransactionAmountEntityVO;
import com.cykj.pos.domain.vo.WalletVO;
import com.cykj.pos.mapper.BizMerchTransactionsMapper;
import com.cykj.pos.mapper.BizMerchantInfoMapper;
import com.cykj.pos.profit.dto.ActivateReachDTO;
import com.cykj.pos.profit.dto.MerchantInfoDTO;
import com.cykj.pos.profit.dto.TransDataDTO;
import com.cykj.pos.profit.dto.TransactionsDTO;
import com.cykj.pos.service.IBizMerchTransactionsService;
import com.cykj.pos.service.IBizMerchantService;
import com.cykj.pos.test.DESUtil;
import com.cykj.pos.util.DateUtils;
import com.cykj.pos.util.HttpUtil;
import com.cykj.pos.util.LoginUserUtils;
import com.cykj.system.mapper.SysDeptMapper;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 商户交易记录Service业务层处理
 *
 * @author ningbingwu
 * @date 2021-01-29
 */
@Service
public class BizMerchTransactionsServiceImpl extends ServiceImpl<BizMerchTransactionsMapper, BizMerchTransactions> implements IBizMerchTransactionsService {

    private static final String DATE_FORMATTER = "yyyy-MM";
    @Resource
    private BizMerchTransactionsMapper merchTransactionsMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private IBizMerchantService merchantService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<BizMerchTransactions> queryList(BizMerchTransactions bizMerchTransactions) {
        LambdaQueryWrapper<BizMerchTransactions> lqw = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(bizMerchTransactions.getInnerMerchCode())) {
            lqw.eq(BizMerchTransactions::getInnerMerchCode, bizMerchTransactions.getInnerMerchCode());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getMerchFlagCode())) {
            lqw.eq(BizMerchTransactions::getMerchFlagCode, bizMerchTransactions.getMerchFlagCode());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getOrderId())) {
            lqw.eq(BizMerchTransactions::getOrderId, bizMerchTransactions.getOrderId());
        }
        if (bizMerchTransactions.getTransAmount() != null) {
            lqw.eq(BizMerchTransactions::getTransAmount, bizMerchTransactions.getTransAmount());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getIdTxn())) {
            lqw.eq(BizMerchTransactions::getIdTxn, bizMerchTransactions.getIdTxn());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getProductCode())) {
            lqw.eq(BizMerchTransactions::getProductCode, bizMerchTransactions.getProductCode());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getBankAuthCode())) {
            lqw.eq(BizMerchTransactions::getBankAuthCode, bizMerchTransactions.getBankAuthCode());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getDiscountRateFlag())) {
            lqw.eq(BizMerchTransactions::getDiscountRateFlag, bizMerchTransactions.getDiscountRateFlag());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getStatus())) {
            lqw.eq(BizMerchTransactions::getStatus, bizMerchTransactions.getStatus());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getErrorCode())) {
            lqw.eq(BizMerchTransactions::getErrorCode, bizMerchTransactions.getErrorCode());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getErrorMsg())) {
            lqw.eq(BizMerchTransactions::getErrorMsg, bizMerchTransactions.getErrorMsg());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getTransDate())) {
            lqw.eq(BizMerchTransactions::getTransDate, bizMerchTransactions.getTransDate());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getServiceEntryMode())) {
            lqw.eq(BizMerchTransactions::getServiceEntryMode, bizMerchTransactions.getServiceEntryMode());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getCardType())) {
            lqw.eq(BizMerchTransactions::getCardType, bizMerchTransactions.getCardType());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getPosCode())) {
            lqw.eq(BizMerchTransactions::getPosCode, bizMerchTransactions.getPosCode());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getDeviceType())) {
            lqw.eq(BizMerchTransactions::getDeviceType, bizMerchTransactions.getDeviceType());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getUserName())) {
            lqw.like(BizMerchTransactions::getUserName, bizMerchTransactions.getUserName());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getPhoneNo())) {
            lqw.eq(BizMerchTransactions::getPhoneNo, bizMerchTransactions.getPhoneNo());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getStoreCachierFlag())) {
            lqw.eq(BizMerchTransactions::getStoreCachierFlag, bizMerchTransactions.getStoreCachierFlag());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getReceiptType())) {
            lqw.eq(BizMerchTransactions::getReceiptType, bizMerchTransactions.getReceiptType());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getS0PackageFlag())) {
            lqw.eq(BizMerchTransactions::getS0PackageFlag, bizMerchTransactions.getS0PackageFlag());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getSecondOrgId())) {
            lqw.eq(BizMerchTransactions::getSecondOrgId, bizMerchTransactions.getSecondOrgId());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getDirectlyOrgId())) {
            lqw.eq(BizMerchTransactions::getDirectlyOrgId, bizMerchTransactions.getDirectlyOrgId());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getSpecialMode())) {
            lqw.eq(BizMerchTransactions::getSpecialMode, bizMerchTransactions.getSpecialMode());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getEsimFlag())) {
            lqw.eq(BizMerchTransactions::getEsimFlag, bizMerchTransactions.getEsimFlag());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getIdCardNo())) {
            lqw.eq(BizMerchTransactions::getIdCardNo, bizMerchTransactions.getIdCardNo());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getAuthMerchId())) {
            lqw.eq(BizMerchTransactions::getAuthMerchId, bizMerchTransactions.getAuthMerchId());
        }
        if (StringUtils.isNotBlank(bizMerchTransactions.getAuthTerminalId())) {
            lqw.eq(BizMerchTransactions::getAuthTerminalId, bizMerchTransactions.getAuthTerminalId());
        }
        return this.list(lqw);
    }

    /**
     * @author: haoran
     * @date: 2022/7/28
     * 方法名称： 所有交易记录列表
     */
    @Override
    public List<BizMerchTransactions> queryLists(BizMerchTransactions bizMerchTransactions) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        BizMerchTransactionsDTO dto = new BizMerchTransactionsDTO();
        dto.setPosCode(bizMerchTransactions.getPosCode());
        dto.setUserName(bizMerchTransactions.getUserName());
        dto.setMerchId(bizMerchTransactions.getMerchId());
        dto.setWhetherSteal(bizMerchTransactions.getWhetherSteal());
        dto.setParams(bizMerchTransactions.getParams());
        // 获取当前用户信息
        SysUser sysUser= SecurityUtils.getLoginUser().getUser();
        // 如果登录人id = 1， 就直接改成id = 2
        if (sysUser.getUserId() == 1) {
            sysUser.setUserId(2L);
        }
        if (dto.getMerchId() == null) {
            // 查询本人merchId
            Long merchId = merchTransactionsMapper.selectMerchId(sysUser.getUserId());
            dto.setLoginMerchId(merchId);
        }
        if("1".equals(bizMerchTransactions.getContains())&&dto.getMerchId() != null){
            dto.setLoginMerchId(dto.getMerchId());
            dto.setMerchId(null);
        }
        // 查询本人的机构后缀
        String suffix = merchTransactionsMapper.selectSuffix(sysUser.getUserId());
        String tableName ="";
        // 拼接机构表名称
        if(StringUtils.isNotBlank(suffix)){
            tableName="biz_transaction_amount_" + suffix;
        }else{
            tableName="biz_transaction_amount";
        }
        dto.setTableName(tableName);
        String start = " 00:00:00";
        String end = " 23:59:59";
        if(bizMerchTransactions.getParams().isEmpty()) {
            dto.setStartTime(df.format(new Date()) + start);
            dto.setEndTime(df.format(new Date()) + end);
        } else {
            dto.setStartTime(bizMerchTransactions.getParams().get("beginTime").toString() + start);
            dto.setEndTime(bizMerchTransactions.getParams().get("endTime").toString() + end);
        }
        if (bizMerchTransactions.getPageNo() != null && bizMerchTransactions.getPageSize() != null) {
            PageHelper.startPage(bizMerchTransactions.getPageNo(), bizMerchTransactions.getPageSize());
        }
        List<BizMerchTransactions> list = merchTransactionsMapper.queryLists(dto);
        Boolean b=merchTransactionsMapper.selectNoUser(sysUser.getUserId())==0;
        for (BizMerchTransactions bizMerchTransactions1 : list) {
            bizMerchTransactions1.setUserId(sysUser.getUserId());
            if(b&&"1".equals(bizMerchTransactions1.getSilenceType())){
                bizMerchTransactions1.setFeeName(bizMerchTransactions1.getActualFeeName());
                bizMerchTransactions1.setAddiAmount(bizMerchTransactions1.getActualAddiAmount());
            }
        }
        return list;
    }
    /**
     * @author: haoran
     * @date: 2022/7/29
     * 方法名称： 交易记录
     */
    @Override
    public List<BizMerchTransactions> listsPartner1(BizMerchTransactions bizMerchTransactions) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        BizMerchTransactionsDTO dto = new BizMerchTransactionsDTO();
        dto.setPosCode(bizMerchTransactions.getPosCode());
        dto.setUserName(bizMerchTransactions.getUserName());
        dto.setMerchId(bizMerchTransactions.getMerchId());
        dto.setWhetherSteal(bizMerchTransactions.getWhetherSteal());
        dto.setParams(bizMerchTransactions.getParams());
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser.getUserId() == 1) {
            sysUser.setUserId(2L);
        }
        // 查询本人merchId
        if (dto.getMerchId() == null) {
            // 查询本人merchId
            Long merchId = merchTransactionsMapper.selectMerchId(sysUser.getUserId());
            dto.setMerchId(merchId);
        }

        // 查询本人的机构后缀
        String suffix = merchTransactionsMapper.selectSuffix(sysUser.getUserId());
        String tableName ="";
        // 拼接机构表名称
        if(StringUtils.isNotBlank(suffix)){
            tableName="biz_transaction_amount_" + suffix;
        }else{
            tableName="biz_transaction_amount";
        }
        dto.setTableName(tableName);
        String start = " 00:00:00";
        String end = " 23:59:59";
        if(bizMerchTransactions.getParams().isEmpty()) {
            dto.setStartTime(df.format(new Date()) + start);
            dto.setEndTime(df.format(new Date()) + end);
        } else {
            dto.setStartTime(bizMerchTransactions.getParams().get("beginTime").toString() + start);
            dto.setEndTime(bizMerchTransactions.getParams().get("endTime").toString() + end);
        }
        if (bizMerchTransactions.getPageNo() != null && bizMerchTransactions.getPageSize() != null) {
            PageHelper.startPage(bizMerchTransactions.getPageNo(), bizMerchTransactions.getPageSize());
        }
        List<BizMerchTransactions> list = merchTransactionsMapper.listsPartner1(dto);
        return list;
    }

    @Override
    public BizMerchBillTurnoverDTO turnoverlist(BizMerchTransactions bizMerchTransactions) {
        //当前时间
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Object> data = bizMerchTransactions.getParams();
        if (!data.isEmpty()) {
            Object beginTime = data.get("beginTime");
            Object endTime = data.get("endTime");
            String beginTimestr = beginTime.toString();
            String endTimestr = endTime.toString();
            bizMerchTransactions.setBeginTime(beginTimestr);
            bizMerchTransactions.setEndTime(endTimestr);
        }else {
            bizMerchTransactions.setHostDate(format.format(date));
        }
        SysUser sysUser= SecurityUtils.getLoginUser().getUser();
        // 如果登录人id = 1， 就直接改成id = 2
        if (sysUser.getUserId() == 1) {
            sysUser.setUserId(2L);
        }
        if (bizMerchTransactions.getMerchId() == null) {
            // 查询本人merchId
            Long merchId = merchTransactionsMapper.selectMerchId(sysUser.getUserId());
            bizMerchTransactions.setLoginMerchId(merchId);
        }
        SysDept dept=sysDeptMapper.selectDeptById(sysUser.getDeptId());
        if(!dept.getDeptName().equals("支付助手总部")){
            bizMerchTransactions.setOrgnname(dept.getDeptName());
        }
        BizMerchBillTurnoverDTO bizMerchBillTurnoverDTO=new BizMerchBillTurnoverDTO();
        /*所有服务费*/
        BizMerchBill bizMerchBill1 = merchTransactionsMapper.b1amount(bizMerchTransactions);
        /*所有分润*/
        BizMerchBill bizMerchBill2 = merchTransactionsMapper.b2amount(bizMerchTransactions);
        /*所有流量费*/
        BizMerchBill bizMerchBill3 = merchTransactionsMapper.b3amount(bizMerchTransactions);
        bizMerchBillTurnoverDTO.setBamount(bizMerchBill1.getAmount().add(bizMerchBill2.getAmount()).add(bizMerchBill3.getAmount()));
        bizMerchBillTurnoverDTO.setB1amount(bizMerchBill1.getAmount());
        bizMerchBillTurnoverDTO.setB2amount(bizMerchBill2.getAmount());
        bizMerchBillTurnoverDTO.setB3amount(bizMerchBill3.getAmount());
        return bizMerchBillTurnoverDTO;
    }

    @Override
    public List<BizMerchTransactions> listsPartner(BizMerchTransactions bizMerchTransactions) {
        SysUser sysUserman = SecurityUtils.getLoginUser().getUser();
        if (sysUserman.getUserId() == 1) {
            sysUserman.setUserId(2L);
        }
        //当前时间
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //通过user_id  获取merch_Id
        /*BizMerchant bizMerchant=merchTransactionsMapper.selectMerchant(sysUserman.getUserId());*/
        Map<String, Object> data = bizMerchTransactions.getParams();
        if (!data.isEmpty()) {
            Object beginTime = data.get("beginTime");
            Object endTime = data.get("endTime");
            String beginTimestr = beginTime.toString();
            String endTimestr = endTime.toString();
            bizMerchTransactions.setBeginTime(beginTimestr);
            bizMerchTransactions.setEndTime(endTimestr);
        } else {
            bizMerchTransactions.setHostDate(format.format(date).substring(0, 10));
        }
        bizMerchTransactions.setMerchIdPros(sysUserman.getUserId());
        List<BizMerchTransactions> merchTransactions = merchTransactionsMapper.listsPartner(bizMerchTransactions);
        if (sysUserman.getUserId() != 2) {
            for (BizMerchTransactions bizMerchTransactions1 : merchTransactions) {
                //FeeName是否存在+
                boolean status = bizMerchTransactions1.getFeeName().contains("+");
                if (status) {
                    //根据 获取  +  的位置  截取  +  前几位数据
                    bizMerchTransactions1.setFeeName(bizMerchTransactions1.getFeeName().substring(0, bizMerchTransactions1.getFeeName().indexOf("+")));
                }
            }
        }
        for (BizMerchTransactions bizMerchTransactions1 : merchTransactions) {
            bizMerchTransactions1.setMerchIdPros(sysUserman.getUserId());
        }
        return merchTransactions;
    }

    @Override
    public List<BizMerchTransactions> listsAsscend(BizMerchTransactions bizMerchTransactions) {
        SysUser sysUserman = SecurityUtils.getLoginUser().getUser();
        if (sysUserman.getUserId() == 1) {
            sysUserman.setUserId(2L);
        }
        //通过user_id  获取merch_Id
        BizMerchant bizMerchant=merchTransactionsMapper.selectMerchant(sysUserman.getUserId());
        bizMerchTransactions.setLoginMerchId(bizMerchant.getMerchId());
        //当前时间
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> data = bizMerchTransactions.getParams();
        if (!data.isEmpty()) {
            Object beginTime = data.get("beginTime");
            Object endTime = data.get("endTime");
            String beginTimestr = beginTime.toString();
            String endTimestr = endTime.toString();
            bizMerchTransactions.setBeginTime(beginTimestr);
            bizMerchTransactions.setEndTime(endTimestr);
        }else {
            bizMerchTransactions.setHostDate(format.format(date).substring(0, 10));
        }
        bizMerchTransactions.setMerchIdPros(sysUserman.getUserId());
        if (bizMerchTransactions.getPageNo() != null && bizMerchTransactions.getPageSize() != null) {
            PageHelper.startPage(bizMerchTransactions.getPageNo(), bizMerchTransactions.getPageSize());
        }
        List<BizMerchTransactions> merchTransactions = merchTransactionsMapper.listsAsscend(bizMerchTransactions);
        if (sysUserman.getUserId() != 2) {
            for (BizMerchTransactions bizMerchTransactions1 : merchTransactions) {
                //FeeName是否存在+
                boolean status = bizMerchTransactions1.getFeeName().contains("+");
                if (status) {
                    //根据 获取  +  的位置  截取  +  前几位数据
                    bizMerchTransactions1.setFeeName(bizMerchTransactions1.getFeeName().substring(0, bizMerchTransactions1.getFeeName().indexOf("+")));
                }
            }
        }
        for (BizMerchTransactions bizMerchTransactions1 : merchTransactions) {
            bizMerchTransactions1.setMerchIdPros(sysUserman.getUserId());
        }
        return merchTransactions;
    }

    @Override
    public List<BizMerchTransactions> listsReturn(BizMerchTransactions bizMerchTransactions) {
        System.out.println("+++///" + bizMerchTransactions);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        BizMerchTransactionsDTO dto = new BizMerchTransactionsDTO();
        dto.setParams(bizMerchTransactions.getParams());
        dto.setFlowState(bizMerchTransactions.getFlowState());
        dto.setPosCode(bizMerchTransactions.getPosCode());
        dto.setUserName(bizMerchTransactions.getUserName());
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        // 如果没有选择merchId，就用当前登录人查询
        if (bizMerchTransactions.getMerchId() == null) {
            if (sysUser.getUserId() == 1) {
                sysUser.setUserId(2L);
            }
            // 查询本人merchId
            Long merchId = merchTransactionsMapper.selectMerchId(sysUser.getUserId());
            dto.setLoginMerchId(merchId);
        } else {
            dto.setMerchId(bizMerchTransactions.getMerchId());
        }
        // 查询本人的机构后缀
        String suffix = merchTransactionsMapper.selectSuffix(sysUser.getUserId());
        String tableName ="";
        // 拼接机构表名称
        if(StringUtils.isNotBlank(suffix)){
            tableName="biz_transaction_amount_" + suffix;
        }else{
            tableName="biz_transaction_amount";
        }
        dto.setTableName(tableName);
        String start = " 00:00:00";
        String end = " 23:59:59";
        if(bizMerchTransactions.getParams().isEmpty()) {
            dto.setStartTime(df.format(new Date()) + start);
            dto.setEndTime(df.format(new Date()) + end);
        } else {
            dto.setStartTime(bizMerchTransactions.getParams().get("beginTime").toString() + start);
            dto.setEndTime(bizMerchTransactions.getParams().get("endTime").toString() + end);
        }
        if (bizMerchTransactions.getPageNo() != null && bizMerchTransactions.getPageSize() != null) {
            PageHelper.startPage(bizMerchTransactions.getPageNo(), bizMerchTransactions.getPageSize());
        }
        System.out.println("+++" + dto);
        List<BizMerchTransactions> list = merchTransactionsMapper.listsReturn(dto);
        return list;
    }

    @Override
    public List<BizFeesChargedDTO> tramcBilling(BizFeesChargedDTO bizFeesChargedDTO) {
        Map<String, Object> data = bizFeesChargedDTO.getParams();
        if (!data.isEmpty()) {
            Object beginTime = data.get("beginTime");
            Object endTime = data.get("endTime");
            String beginTimestr = beginTime.toString();
            String endTimestr = endTime.toString();
            bizFeesChargedDTO.setBeginTime(beginTimestr.replaceAll("-", ""));
            bizFeesChargedDTO.setEndTime(endTimestr.replaceAll("-", ""));
        }
        List<BizFeesChargedDTO> merchTransactions = merchTransactionsMapper.tramcBilling(bizFeesChargedDTO);
        for (BizFeesChargedDTO bizFeesChargedDTO1:merchTransactions){
            StringBuffer stringBuilder1=new StringBuffer(bizFeesChargedDTO1.getHostDate());
            stringBuilder1.insert(4,"-");
            stringBuilder1.insert(7,"-");
            bizFeesChargedDTO1.setHostDate(String.valueOf(stringBuilder1));
        }
        return merchTransactions;
    }

    @Override
    public List<BizProfitDeatail> queryListAlls(String uuId) {
        List<BizProfitDeatail> bizProfitDeatails = merchTransactionsMapper.queryListAlls(Long.valueOf(uuId));
        String silenceType=merchTransactionsMapper.getSilenceType(Long.valueOf(uuId));
        SysUser sysUserman = SecurityUtils.getLoginUser().getUser();
        if(merchTransactionsMapper.selectNoUser(sysUserman.getUserId())==0&&"1".equals(silenceType)){
            for(BizProfitDeatail a : bizProfitDeatails){
                a.setMoney(a.getActualMoney());
                a.setRate(a.getActualRate());
            }
        }
        return bizProfitDeatails;
    }

    @Override
    public List<CashbackRecordDTO> listReturnAlls(String uuId) {
        List<CashbackRecordDTO> bizProfitDeatails = merchTransactionsMapper.listReturnAlls(Long.valueOf(uuId));
        return bizProfitDeatails;
    }

    @Override
    public List<CashbackRecordDTO> listTramcBillingAlls(String uuId) {
        List<CashbackRecordDTO> bizProfitDeatails = merchTransactionsMapper.listTramcBillingAlls(Long.valueOf(uuId));
        return bizProfitDeatails;
    }

    @Override
    public StealSwitchDTO listStealSwitch(StealSwitchDTO stealSwitchDTO) {
        StealSwitchDTO stealSwitchDTOs = merchTransactionsMapper.listStealSwitch(stealSwitchDTO);
        return stealSwitchDTOs;
    }

    @Override
    public AscendSwitchDTO listAscendSwitch(AscendSwitchDTO ascendSwitchDTO) {
        AscendSwitchDTO ascendSwitchDTO1 = merchTransactionsMapper.listAscendSwitch(ascendSwitchDTO);
        return ascendSwitchDTO1;
    }

    @Override
    public int stealupdate(StealSwitchDTO stealSwitchDTO) {
        int row = merchTransactionsMapper.stealupdate(stealSwitchDTO);
        return row;
    }
    @Override
    public int ascendupdate(AscendSwitchDTO ascendSwitchDTO) {
        int row = merchTransactionsMapper.ascendupdate(ascendSwitchDTO);
        return row;
    }

    @Override
    public int estimateIsPass(EstimateIsPassDTO estimateIsPassDTO) {
        SysUser sysUserman = SecurityUtils.getLoginUser().getUser();
        if (sysUserman.getUserId()==1l){
            estimateIsPassDTO.setUserId(2l);
        }else {
            estimateIsPassDTO.setUserId(sysUserman.getUserId());
        }
        int row = merchTransactionsMapper.estimateIsPass(estimateIsPassDTO);
        return row;
    }

    @Override
    public int estimateUpdatePass(EstimateIsPassDTO estimateIsPassDTO) {
        SysUser sysUserman = SecurityUtils.getLoginUser().getUser();
        if (sysUserman.getUserId()==1l){
            estimateIsPassDTO.setUserId(2l);
        }else {
            estimateIsPassDTO.setUserId(sysUserman.getUserId());
        }
        int row = merchTransactionsMapper.estimateUpdatePass(estimateIsPassDTO);
        return row;
    }

    @Override
    public List<BizMerchTransactions> listss() {
        List<BizMerchTransactions> merchTransactions = merchTransactionsMapper.listss();
        for (BizMerchTransactions merchTransactions1 : merchTransactions) {
            if (merchTransactions1.getHostDate().length() < 9) {
                String transDate = merchTransactions1.getHostDate() + " " + merchTransactions1.getHostTime();
                StringBuilder stringBuilder = new StringBuilder(transDate);
                stringBuilder.insert(6, "-");
                stringBuilder.insert(4, "-");
                stringBuilder.insert(10, " ");
                stringBuilder.insert(14, ":");
                stringBuilder.insert(17, ":");
                BizMerchTransactions bizMerchTransactionlists = new BizMerchTransactions();
                bizMerchTransactionlists.setId(merchTransactions1.getId());
                bizMerchTransactionlists.setHostDate(String.valueOf(stringBuilder));
                merchTransactionsMapper.updatalists(bizMerchTransactionlists);
            }
        }
        return merchTransactions;
    }

    @Override
    public BizMerchTransactions getErrorCause(Long Id) {
        return merchTransactionsMapper.getErrorCause(Id);
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<BizMerchTransactions> getMonthlyTransRecordsByMerchId(Long merchId) {
        String formatedDate = DateUtils.getCaculateYearAndMonth("last", DATE_FORMATTER);
        String sql = "select * from biz_merch_transactions t where t.pos_code in (select p.pos_code from biz_pos_machine p " +
                "where FIND_IN_SET(p.merch_id,findMerchSubNode(?))) and t.trans_date like  CONCAT(?,'%')";
        return jdbcTemplate.query(sql, new Object[]{merchId, formatedDate},
                new BeanPropertyRowMapper<>(BizMerchTransactions.class));
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<BizMerchTransactions> getMonthlyTransRecordsByMerchId(String caculatePeriod, Long merchId) {
        String sql = "select * from biz_merch_transactions t where t.pos_code in (select p.pos_code from biz_pos_machine p " +
                "where FIND_IN_SET(p.merch_id,findMerchSubNode(?))) and t.trans_date like  CONCAT(?,'%')";
        return jdbcTemplate.query(sql, new Object[]{merchId, caculatePeriod},
                new BeanPropertyRowMapper<>(BizMerchTransactions.class));
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<BizMerchTransactions> getMonthlyTransRecordsByMerchId(String caculatePeriod, Long merchId, int pageNo, int pageSize) {
        int start = (pageNo - 1) * pageSize;
        String sql = "select * from biz_merch_transactions t where t.pos_code in (select p.pos_code from biz_pos_machine p " +
                "where FIND_IN_SET(p.merch_id,findMerchSubNode(?))) and t.trans_date like  CONCAT(?,'%') LIMIT ?,?";
        return jdbcTemplate.query(sql, new Object[]{merchId, caculatePeriod, start, pageSize},
                new BeanPropertyRowMapper<>(BizMerchTransactions.class));
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<BizMerchTransactions> getMonthlyTransRecordsByMerchId(Long merchId, int pageNo, int pageSize) {
        int start = (pageNo - 1) * pageSize;
        String formatedDate = DateUtils.getCaculateYearAndMonth("last", DATE_FORMATTER);
        String sql = "select * from biz_merch_transactions t where t.pos_code in (select p.pos_code from biz_pos_machine p " +
                "where FIND_IN_SET(p.merch_id,findMerchSubNode(?))) and t.trans_date like  CONCAT(?,'%') LIMIT ?,?";
        return jdbcTemplate.query(sql, new Object[]{merchId, formatedDate, start, pageSize},
                new BeanPropertyRowMapper<>(BizMerchTransactions.class));
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public BigDecimal getMonthlyTransAmountByMerchId(String caculatePeriod, Long merchId) {
        String sql = "select sum(trans_amount) from biz_merch_transactions t where t.pos_code in (select p.pos_code from biz_pos_machine p " +
                "where FIND_IN_SET(p.merch_id,findMerchSubNode(?))) and t.trans_date like CONCAT(?,'%')";
        BigDecimal transAmount = jdbcTemplate.queryForObject(sql, new Object[]{merchId, caculatePeriod}, BigDecimal.class);
        return transAmount == null ? BigDecimal.ZERO : transAmount;
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public BigDecimal getMonthlyTransAmountByMerchId(Long merchId) { // 获取当前月份
        String formatedDate = DateUtils.getCaculateYearAndMonth("", DATE_FORMATTER);
        String sql = "select sum(trans_amount) from biz_merch_transactions t where t.pos_code in (select p.pos_code from biz_pos_machine p " +
                "where p.pos_activate_status=2 and FIND_IN_SET(p.merch_id,findMerchSubNode(?))) and t.error_msg='交易成功' and t.trans_date like CONCAT(?,'%')";
        BigDecimal transAmount = jdbcTemplate.queryForObject(sql, new Object[]{merchId, formatedDate}, BigDecimal.class);
        return transAmount == null ? BigDecimal.ZERO : transAmount;
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public BigDecimal getMonthlyTransAmountByMerchId(Long merchId, String month) { // 获取某个月份的销售总金额
        String formatedDate = DateUtils.getCaculateYearAndMonth(month, DATE_FORMATTER);
        String sql = "select sum(trans_amount) from biz_merch_transactions t where t.pos_code in (select p.pos_code from biz_pos_machine p " +
                "where p.pos_activate_status=2 and FIND_IN_SET(p.merch_id,findMerchSubNode(?))) and t.error_msg='交易成功' and t.trans_date like CONCAT(?,'%')";
        BigDecimal transAmount = jdbcTemplate.queryForObject(sql, new Object[]{merchId, formatedDate}, BigDecimal.class);
        return transAmount == null ? BigDecimal.ZERO : transAmount;
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public BigDecimal getMonthlyMerchantTransAmountByMerchId(Long merchId) {
        String formatedDate = DateUtils.getCaculateYearAndMonth("this", DATE_FORMATTER);
        String sql = "select sum(trans_amount) from biz_merch_transactions t where t.pos_code in (select p.pos_code from biz_pos_machine p " +
                "where p.merch_id=?) and t.error_msg='交易成功' and t.trans_date like CONCAT(?,'%')";
        BigDecimal transAmount = jdbcTemplate.queryForObject(sql, new Object[]{merchId, formatedDate}, BigDecimal.class);
        return transAmount == null ? BigDecimal.ZERO : transAmount;
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public BigDecimal getTotalTransAmountByMerchId(Long merchantId) {
        /*
        String formatedDate = DateUtils.getCaculateYearAndMonth("",DATE_FORMATTER);
        String sql = "select sum(trans_amount) from biz_merch_transactions t where t.pos_code in (select p.pos_code from biz_pos_machine p " +
                "where FIND_IN_SET(p.merch_id,findMerchSubNode(?))) and t.trans_date like CONCAT(?,'%')";
        BigDecimal transAmount = jdbcTemplate.queryForObject(sql,new Object[]{merchId,formatedDate},BigDecimal.class);
        return transAmount == null?BigDecimal.ZERO:transAmount;
         */
        String sql = "select sum(trans_amount) from biz_merch_transactions t where t.pos_code in (select p.pos_code from biz_pos_machine p " +
                "where p.merch_id=?)";
        BigDecimal transAmount = jdbcTemplate.queryForObject(sql, new Object[]{merchantId}, BigDecimal.class);
        return transAmount == null ? BigDecimal.ZERO : transAmount;
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<BizMerchTransactions> queryDealNum(String id) {
        /*LambdaQueryWrapper<BizMerchTransactions> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(BizMerchTransactions::getPosCode,id);
        List<BizMerchTransactions> list = this.list(wrapper);*/
        // 获取当前的用户
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();
        // 查询本人的机构后缀
        String suffix = merchTransactionsMapper.selectSuffix(sysUser.getUserId());
        String tableName ="";
        // 拼接机构表名称
        if(StringUtils.isNotBlank(suffix)){
            tableName="biz_transaction_amount_" + suffix;
        }else{
            tableName="biz_transaction_amount";
        }
        List<BizMerchTransactions> list = merchTransactionsMapper.queryDealNum(id, tableName);
        return list;
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public BigDecimal queryNowMonthDeal(MerchantInfoDTO merchantInfoDTO) {
        // 截取当月
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM- dd HH:mm:ss");
        String nowDate = dateFormat.format(date).substring(0, 7);
        merchantInfoDTO.setQueryMonth(nowDate);
        // 获取当前的用户
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();
        // 查询本人的机构后缀
        String suffix = merchTransactionsMapper.selectSuffix(sysUser.getUserId());
        String tableName ="";
        // 拼接机构表名称
        if(StringUtils.isNotBlank(suffix)){
            tableName="biz_transaction_amount_" + suffix;
        }else{
            tableName="biz_transaction_amount";
        }
        merchantInfoDTO.setTableName(tableName);
        TransactionsDTO transactionsDTO = merchTransactionsMapper.queryNowMonthDeal(merchantInfoDTO);
        if (transactionsDTO == null) {
            BigDecimal bigDecimal = new BigDecimal("0");
            return bigDecimal;
        }
        return transactionsDTO.getThisMonthAmount();
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public TransactionsDTO queryNowMonthDealWay(MerchantInfoDTO merchantInfoDTO) {
        String thisMonth = DateUtils.Date2String(new Date(), "yyyy-MM");// 截取当月
        merchantInfoDTO.setQueryMonth(thisMonth);
        TransactionsDTO transactionsDTO = merchTransactionsMapper.queryNowMonthDealWay(merchantInfoDTO);
        BigDecimal bigDecimal = new BigDecimal("0");
        // 查出来的值有肯能为null 需要赋值
        if (transactionsDTO == null) {
            TransactionsDTO transactionsDTO1 = new TransactionsDTO();
            transactionsDTO1.setThisMonthAmountSlotCard(bigDecimal);
            transactionsDTO1.setThisMonthAmountQuickPass(bigDecimal);
            transactionsDTO1.setThisMonthAmountScanPay(bigDecimal);
            return transactionsDTO1;
        }
        if (transactionsDTO.getThisMonthAmountSlotCard() == null) {
            transactionsDTO.setThisMonthAmountSlotCard(bigDecimal);
        }
        if (transactionsDTO.getThisMonthAmountQuickPass() == null) {
            transactionsDTO.setThisMonthAmountQuickPass(bigDecimal);
        }
        if (transactionsDTO.getThisMonthAmountScanPay() == null) {
            transactionsDTO.setThisMonthAmountScanPay(bigDecimal);
        }
        return transactionsDTO;
    }

    @Override
    public List<ActivateReachDTO> queryActivatePosMonthAmount(BizPosMachineStatusRecords posInfo) {
        List<ActivateReachDTO> list = new ArrayList<ActivateReachDTO>();
        try {
            Date date = new Date();
            String activateTime = posInfo.getActiveTime().substring(0, 10);// 截取到日
            System.out.println(activateTime);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date stringToDate = null;

            stringToDate = simpleDateFormat.parse(activateTime);// 字符串日期转换成 date


            for (int i = 0; i >= 0; i++) {
                //Date finalTime = DateUtils.addDays(overTime,30);// 第二次在上一次时间上加30天
                String time = DateUtils.dateSubMonth(date, -i);
                ActivateReachDTO activateReachDTO = new ActivateReachDTO();
                activateReachDTO.setTime(time);
                activateReachDTO.setStartTime(activateTime);// 存入开始时间
                String overEndTime = DateUtils.dateSubOne(stringToDate, 30);
                //String overEndTime = simpleDateFormat.format(overTime);
                activateReachDTO.setEndTime(overEndTime);// 存入结束时间
                activateReachDTO.setSnCode(posInfo.getSnCode());
                Date overTime = null;
                overTime = simpleDateFormat.parse(activateTime);
                if (overTime.getTime() > date.getTime()) { //结束时间大于当前时间
                    break;
                }
                activateTime = overEndTime;

                stringToDate = simpleDateFormat.parse(activateTime);

                list.add(i, activateReachDTO);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        List<ActivateReachDTO> overList = new ArrayList<ActivateReachDTO>();
        for (int i = 0; i < list.size(); i++) {
            ActivateReachDTO activateReachDTO = merchTransactionsMapper.queryActivatePosMonthAmount(list.get(i));
            activateReachDTO.setTime(list.get(i).getTime());
            overList.add(i, activateReachDTO);
        }
        BigDecimal bigDecimal = new BigDecimal("10000");
        for (int i = 0; i < overList.size(); i++) {
            // 判断是否达标
            if (overList.get(i).getMonthAmount().compareTo(bigDecimal) == 1 || overList.get(i).getMonthAmount().compareTo(bigDecimal) == 0) {
                overList.get(i).setReach(0);
            } else if (overList.get(i).getMonthAmount().compareTo(bigDecimal) == -1) {
                overList.get(i).setReach(1);
            }
        }
        return overList;
    }

    /**
     * 存储pos1.0交易信息
     *
     * @param sy
     * @return
     */
    @Override
    @Transactional
    public int insertPosOneTransactionAmount(SynchronizationDataDTO sy) {
        BizMerchTransactions bizMerchTransactions = new BizMerchTransactions();
        bizMerchTransactions.setMerchFlagCode(sy.getMerchant_no());
        bizMerchTransactions.setPosCode(sy.getPos_sn());// 设备号
        BigDecimal transAmount = new BigDecimal(sy.getAmnount());// 交易金额
        bizMerchTransactions.setTransAmount(transAmount);
        String hostDate = String.valueOf(sy.getHost_date());// 交易时间
        String date = DateUtils.dateConvertion(hostDate);
        bizMerchTransactions.setTransDate(date);// 交易时间
        //bizMerchTransactions.setOrderId();
        bizMerchTransactions.setIdCardNo(sy.getAcq_certificate());// 身份证
        bizMerchTransactions.setUserName(sy.getAcq_name());// 姓名
        if (String.valueOf(sy.getCard_type()).equals("1") || String.valueOf(sy.getCard_type()).equals("2") || String.valueOf(sy.getCard_type()).equals("3") || String.valueOf(sy.getCard_type()).equals("4")) {
            // 刷卡
            bizMerchTransactions.setDiscountRateFlag("0");// 刷卡
        } else {
            // 扫码
            bizMerchTransactions.setDiscountRateFlag(" ");
        }
        bizMerchTransactions.setCardType("001");// 信用卡交易
        if (sy.getHost_ret_code().equals("00")) {
            bizMerchTransactions.setErrorMsg("交易成功");
        } else {
            bizMerchTransactions.setErrorMsg("交易失败");
        }
        bizMerchTransactions.setErrorCode(sy.getHost_ret_code());
        String dateTime = String.valueOf(sy.getHost_date());
        bizMerchTransactions.setTransDate(dateTime);
        bizMerchTransactions.setWhetherSteal("0");
        return merchTransactionsMapper.insert(bizMerchTransactions);
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public BigDecimal queryAllMonthDeal(MerchantInfoDTO merchantInfoDTO) {
        // 获取当前的用户
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();
        // 查询本人的机构后缀
        String suffix = merchTransactionsMapper.selectSuffix(sysUser.getUserId());
        String tableName ="";
        // 拼接机构表名称
        if(StringUtils.isNotBlank(suffix)){
            tableName="biz_transaction_amount_" + suffix;
        }else{
            tableName="biz_transaction_amount";
        }
        merchantInfoDTO.setTableName(tableName);
        TransactionsDTO transactionsDTO = merchTransactionsMapper.queryAllMonthDeal(merchantInfoDTO);
        if (transactionsDTO == null) {
            BigDecimal bigDecimal = new BigDecimal("0");
            return bigDecimal;
        }
        return transactionsDTO.getAddAmount();
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<TransPerformanceDTO> queryMerchantTransactionInfo(TransPerformanceDTO transPerformanceDTO) {
        // 获取用户信息
        Long userId = LoginUserUtils.getLoginUserId();
        transPerformanceDTO.setUserId(userId);
        // 处理分页
        if (transPerformanceDTO.getPageNo() != -1 && transPerformanceDTO.getPageSize() != -1) {
            int start = (transPerformanceDTO.getPageNo() - 1) * transPerformanceDTO.getPageSize();
            transPerformanceDTO.setStart(start);
        }
        // 设置商户id
        BizMerchant merchant = merchantService.getMerchantByUserId(userId);
        transPerformanceDTO.setMerchId(merchant.getMerchId());
        // dimeType查询的维度
        List<TransPerformanceDTO> list = new ArrayList<>();
        if (transPerformanceDTO.getDimeType() != null && transPerformanceDTO.getDimeType() == 1) {
            //日维度
            list = merchTransactionsMapper.selectMerchantDayTransactionInfo(transPerformanceDTO);
        } else if (transPerformanceDTO.getDimeType() != null && transPerformanceDTO.getDimeType() == 2) {
            //月维度查询
            list = merchTransactionsMapper.selectMerchantMonthTransactionInfo(transPerformanceDTO);
        }
        return list;
    }

    @Override
    public List<TransPerformanceDTO> queryTeamTransactionInfo(TransPerformanceDTO transPerformanceDTO) {
        // 获取用户信息
        Long userId = LoginUserUtils.getLoginUserId();
        transPerformanceDTO.setUserId(userId);
        // 处理分页
        if (transPerformanceDTO.getPageNo() != -1 && transPerformanceDTO.getPageSize() != -1) {
            int start = (transPerformanceDTO.getPageNo() - 1) * transPerformanceDTO.getPageSize();
            transPerformanceDTO.setStart(start);
        }
        // 设置商户id
        BizMerchant merchant = merchantService.getMerchantByUserId(userId);
        transPerformanceDTO.setMerchId(merchant.getMerchId());
        // dimeType查询的维度
        List<TransPerformanceDTO> list = new ArrayList<>();
        if (transPerformanceDTO.getDimeType() != null && transPerformanceDTO.getDimeType() == 1) {
            //日维度
            list = merchTransactionsMapper.selectTeamDayTransactionInfo(transPerformanceDTO);
        } else if (transPerformanceDTO.getDimeType() != null && transPerformanceDTO.getDimeType() == 2) {
            //月维度查询
            list = merchTransactionsMapper.selectTeamMonthTransactionInfo(transPerformanceDTO);
        }
        return list;
    }

    @Override
    public List<TransPerformanceDTO> queryAllTransactionInfo(TransPerformanceDTO transPerformanceDTO) {
        // 获取用户信息
        Long userId = LoginUserUtils.getLoginUserId();
        transPerformanceDTO.setUserId(userId);
        // 处理分页
        if (transPerformanceDTO.getPageNo() != -1 && transPerformanceDTO.getPageSize() != -1) {
            int start = (transPerformanceDTO.getPageNo() - 1) * transPerformanceDTO.getPageSize();
            transPerformanceDTO.setStart(start);
        }
        // 设置商户id
        BizMerchant merchant = merchantService.getMerchantByUserId(userId);
        transPerformanceDTO.setMerchId(merchant.getMerchId());
        // dimeType查询的维度
        List<TransPerformanceDTO> list = new ArrayList<>();
        if (transPerformanceDTO.getDimeType() != null && transPerformanceDTO.getDimeType() == 1) {
            //日维度
            list = merchTransactionsMapper.selectAllDayTransactionInfo(transPerformanceDTO);
        } else if (transPerformanceDTO.getDimeType() != null && transPerformanceDTO.getDimeType() == 2) {
            //月维度查询
            list = merchTransactionsMapper.selectAllMonthTransactionInfo(transPerformanceDTO);
        }
        return list;
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<TransactionRecordDTO> findTransactionRecord(TransactionRecord transactionRecord) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 获取我的merchId
        Long merchId = merchTransactionsMapper.findMerchId(transactionRecord.getUserId());
        transactionRecord.setMerchId(merchId);
        // 获取跟我有关的交易记录
        if (StringUtils.isEmpty(transactionRecord.getStartTime())) {
            transactionRecord.setStartTime(simpleDateFormat.format(new Date()));
        }
        // 获取本人所处机构名称后缀
        String suffix = merchTransactionsMapper.selectSuffix(transactionRecord.getUserId());
        String tableName ="";
        // 拼接机构表名称
        if(StringUtils.isNotBlank(suffix)){
            tableName="biz_transaction_amount_" + suffix;
        }else{
            tableName="biz_transaction_amount";
        }
        String s = " 59:59:59";
        String endTime = "";
        if (transactionRecord.getStartTime().length() > 0 && transactionRecord.getEndTime().length() > 0) {
            endTime = transactionRecord.getEndTime() + s;
        }else{
            endTime=simpleDateFormat.format(new Date())+s;
        }
        transactionRecord.setEndTime(endTime);
        transactionRecord.setTableName(tableName);
        List<TransactionRecordDTO> list = merchTransactionsMapper.findTransactionRecord(transactionRecord);
        return list;
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<TransactionRecordDTO> findTransactionRecordNew(TransactionRecord transactionRecord) {
        // 获取当前用户信息
        SysUser sysUser= SecurityUtils.getLoginUser().getUser();
        // 如果登录人id = 1， 就直接改成id = 2
        if (sysUser.getUserId() == 1) {
            sysUser.setUserId(2L);
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 获取我的merchId
        Long merchId = merchTransactionsMapper.findMerchId(transactionRecord.getUserId());
        transactionRecord.setMerchId(merchId);
        // 获取跟我有关的交易记录
        if (StringUtils.isEmpty(transactionRecord.getStartTime())) {
            transactionRecord.setStartTime(simpleDateFormat.format(new Date()));
        }
        // 获取本人所处机构名称后缀
        String suffix = merchTransactionsMapper.selectSuffix(transactionRecord.getUserId());
        String tableName ="";
        // 拼接机构表名称
        if(StringUtils.isNotBlank(suffix)){
            tableName="biz_transaction_amount_" + suffix;
        }else{
            tableName="biz_transaction_amount";
        }
        String s = " 59:59:59";
        String endTime = "";
        if (transactionRecord.getStartTime().length() > 0 && transactionRecord.getEndTime().length() > 0) {
            endTime = transactionRecord.getEndTime() + s;
        }else{
            endTime=simpleDateFormat.format(new Date())+s;
        }
        transactionRecord.setEndTime(endTime);
        transactionRecord.setTableName(tableName);
        List<TransactionRecordDTO> list = merchTransactionsMapper.findTransactionRecordNew(transactionRecord);
        for(TransactionRecordDTO transactionRecordDTO:list){
            if(merchTransactionsMapper.selectNoUser(sysUser.getUserId())==0&&"1".equals(transactionRecordDTO.getSilenceType())){
                transactionRecordDTO.setFl(transactionRecordDTO.getYfl());
            }
        }
        return list;
    }
    @Override
    public int insertbizMerchTransactions(SynchronizationDataDTO sy) {
        BizMerchTransactions bizMerchTransactions = new BizMerchTransactions();
        bizMerchTransactions.setMerchFlagCode(sy.getMerchant_no());
        bizMerchTransactions.setPosCode(sy.getPos_sn());// 设备号
        BigDecimal transAmount = new BigDecimal(sy.getAmnount());// 交易金额
        bizMerchTransactions.setTransAmount(transAmount);
        String hostDate = String.valueOf(sy.getHost_date());// 交易时间
        String date = DateUtils.dateConvertion(hostDate);
        bizMerchTransactions.setTransDate(date);// 交易时间
        //bizMerchTransactions.setOrderId();
        bizMerchTransactions.setIdCardNo(sy.getAcq_certificate());// 身份证
        bizMerchTransactions.setUserName(sy.getAcq_name());// 姓名
        if (String.valueOf(sy.getCard_type()).equals("1") || String.valueOf(sy.getCard_type()).equals("2") || String.valueOf(sy.getCard_type()).equals("3") || String.valueOf(sy.getCard_type()).equals("4")) {
            // 刷卡
            bizMerchTransactions.setDiscountRateFlag("0");// 刷卡
        } else {
            // 扫码
            bizMerchTransactions.setDiscountRateFlag(" ");
        }
        bizMerchTransactions.setCardType("001");// 信用卡交易
        if (sy.getHost_ret_code().equals("00")) {
            bizMerchTransactions.setErrorMsg("交易成功");
        } else {
            bizMerchTransactions.setErrorMsg("交易失败");
        }
        bizMerchTransactions.setErrorCode(sy.getHost_ret_code());
        String hour = sy.getHost_time().substring(0, 2);
        String minute = sy.getHost_time().substring(2, 4);
        String second = sy.getHost_time().substring(4, 6);
        String dateTime = String.valueOf(sy.getHost_date());
        bizMerchTransactions.setTransDate(dateTime);
        bizMerchTransactions.setWhetherSteal("1");
        bizMerchTransactions.setUuid(sy.getUuid());
        return merchTransactionsMapper.insertbizMerchTransactions(bizMerchTransactions);
    }

    public static String dealDate(Date oldDateStr) throws ParseException {
        SimpleDateFormat df1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
        Date date1 = df1.parse(oldDateStr.toString());
        DateFormat df2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        return df2.format(date1);
    }

    @Override
    @Transactional
    public BigDecimal getCoin(SynchronizationDataDTO sy) {
        BigDecimal subtract = new BigDecimal(0);
        String[] split = sy.getFee_name().split("\\+");
        String take = split[1];
        subtract = new BigDecimal(sy.getAddi_amount()).subtract(new BigDecimal(take));
        /*//获取钱包
        WalletVO wallte = merchTransactionsMapper.getWallte();
        //解密
        String profitAmount = DESUtil.decrypt(wallte.getSecretKey(), wallte.getProfitAmount());
        String walletAmount = DESUtil.decrypt(wallte.getSecretKey(), wallte.getWalletAmount());
        //加钱
        BigDecimal profitAmountAfter = new BigDecimal(profitAmount).add(new BigDecimal(take));
        BigDecimal walletAmountAfter = new BigDecimal(walletAmount).add(new BigDecimal(take));
        //加密
        String profitAmountEncrypt = DESUtil.encrypt(wallte.getSecretKey(), profitAmountAfter.toString());
        String walletAmountEncrypt = DESUtil.encrypt(wallte.getSecretKey(), walletAmountAfter.toString());
        //更新钱包
        merchTransactionsMapper.updateWallet(profitAmountEncrypt, walletAmountEncrypt);
        //存记录表
        merchTransactionsMapper.insetRateMoney(sy.getPos_sn(), String.valueOf(sy.getAmnount()), String.valueOf(sy.getAddi_amount()), take,
                sy.getAcq_name(), sy.getFee_name());*/

        return subtract;
    }

    @Override
    public Integer findTransaction(String posSn, String amount, String hostDate,String transType) {
        return merchTransactionsMapper.findTransaction(posSn, amount, hostDate ,transType);
    }

    @Override
    public List<BizMerchTransactions> selectBizMerchTransactions(String snCode) {
        return merchTransactionsMapper.selectBizMerchTransactions(snCode);
    }

    @Override
    public void updateBizMerchTransactionsBySN(String snCode, String fictitiousSnCode) {
        merchTransactionsMapper.updateBizMerchTransactionsBySN(snCode, fictitiousSnCode);
    }

    @Override
    public void insertbizMerchTransactionsUnbund(List<BizMerchTransactions> list, Long merchId, String merchName) {
        for (BizMerchTransactions lists : list) {
            lists.setMerchId(merchId);
            lists.setMerchName(merchName);
            merchTransactionsMapper.insertbizMerchTransactionsUnbund(lists);
        }

    }

    @Override
    public void updateWallet(String addi_amount, Long userId) {
        //拿到钱包 解密  加钱 加密 更新
        BizWallet wallte = merchTransactionsMapper.getBizWallte(userId);
        //解密
        String profitAmount = DESUtil.decrypt(wallte.getSecretKey(), wallte.getProfitAmount());
        String walletAmount = DESUtil.decrypt(wallte.getSecretKey(), wallte.getWalletAmount());
        //加钱
        BigDecimal profitAmountAfter = new BigDecimal(profitAmount).add(new BigDecimal(addi_amount));
        BigDecimal walletAmountAfter = new BigDecimal(walletAmount).add(new BigDecimal(addi_amount));
        //加密
        String profitAmountEncrypt = DESUtil.encrypt(wallte.getSecretKey(), profitAmountAfter.toString());
        String walletAmountEncrypt = DESUtil.encrypt(wallte.getSecretKey(), walletAmountAfter.toString());
        merchTransactionsMapper.updateWalletCoin(profitAmountEncrypt,walletAmountEncrypt, userId);
    }

    @Override
    public void subtractionWallet(String addiAmount, Long userId) {
        BizWallet wallte = merchTransactionsMapper.getBizWallte(userId);
        //解密
        String profitAmount = DESUtil.decrypt(wallte.getSecretKey(), wallte.getProfitAmount());
        String walletAmount = DESUtil.decrypt(wallte.getSecretKey(), wallte.getWalletAmount());
       //减钱
        BigDecimal profitAmountAfter = new BigDecimal(profitAmount).subtract(new BigDecimal(addiAmount));
        BigDecimal walletAmountAfter = new BigDecimal(walletAmount).subtract(new BigDecimal(addiAmount));
        //加密
        String profitAmountEncrypt = DESUtil.encrypt(wallte.getSecretKey(), profitAmountAfter.toString());
        String walletAmountEncrypt = DESUtil.encrypt(wallte.getSecretKey(), walletAmountAfter.toString());
        merchTransactionsMapper.updateWalletCoin(profitAmountEncrypt,walletAmountEncrypt, userId);
    }

    @Override
    public BizTransactionCountDTO selectCountBizMerchTransactions(String sn) {
//        CountBizMerchTransactions countBizMerchTransactions = new CountBizMerchTransactions();
        // 获取当前的用户
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();
        String suffix = merchTransactionsMapper.selectSuffix(sysUser.getUserId());
        String tableName ="";
        // 拼接机构表名称
        if(StringUtils.isNotBlank(suffix)){
            tableName="biz_transaction_amount_" + suffix;
        }else{
            tableName="biz_transaction_amount";
        }
//        countBizMerchTransactions.setSn(sn);
//        countBizMerchTransactions.setTableName(tableName);
//        countBizMerchTransactions.setMerchId(merchId);
//        BizTransactionCountDTO b = merchTransactionsMapper.selectCountBizMerchTransactions(countBizMerchTransactions);
//        b.setSumAmount(merchTransactionsMapper.selectSumAmout(countBizMerchTransactions));
//        return b;
        return merchTransactionsMapper.selectCountBizMerchTransactions(sn, tableName);
    }

    @Override
    public BizTransactionCountDTO selectSumCountBizMerchTransactions(String format, String sn) {
        // 获取当前的用户
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();
        String suffix = merchTransactionsMapper.selectSuffix(sysUser.getUserId());
        String tableName ="";
        // 拼接机构表名称
        if(StringUtils.isNotBlank(suffix)){
            tableName="biz_transaction_amount_" + suffix;
        }else{
            tableName="biz_transaction_amount";
        }
//        BizTransactionCountDTO b = merchTransactionsMapper.selectSumCountBizMerchTransactions(format,sn,tableName);
//        b.setMouthAmount(merchTransactionsMapper.selectMouthAmount(merchId));
//        return b;
        return merchTransactionsMapper.selectSumCountBizMerchTransactions(format,sn,tableName);
    }

    @Override
    public List<BizProfitDeatail> selectBizProfitDeatail(String uuid) {
        return merchTransactionsMapper.selectBizProfitDeatail(uuid);
    }

    @Override
    public SynchronizationDataDTO selectTransaction(String pos_sn, String amnount, String host_date) {
        return merchTransactionsMapper.selectTransaction(pos_sn,amnount,host_date);
    }

    @Override
    public Long selectAndInsertId(String uuid) {
        return merchTransactionsMapper.selectAndInsertId(uuid);
    }

    @Override
    @Transactional
    public void insert(BizTransactionEntity bizTransactionEntity) {
        merchTransactionsMapper.insert(bizTransactionEntity);
    }

    @Override
    public List<BizTransactionAmountEntityVO> selectBizMerchTransactionsByCode(BizMerchantInfo bizMerchantInfo) {
        BizMerchantInfo bizMerchantInfo1 = merchTransactionsMapper.selectMerchantInfo(bizMerchantInfo);
        bizMerchantInfo.setMerchantCode(bizMerchantInfo1.getMerchantCode());
        return merchTransactionsMapper.selectBizMerchTransactionsByCode(bizMerchantInfo);
    }
    @Override
    public AjaxResult getOnlineDetail(TransDataDTO transDataDTO) {
        AjaxResult ajaxResult = AjaxResult.success();
        // 处理分页
        if(transDataDTO.getPageNo()!=-1 && transDataDTO.getPageSize()!=-1){
            int start = (transDataDTO.getPageNo()-1)*transDataDTO.getPageSize();
            transDataDTO.setStart(start);
        }
        List<BizMerchTransactions> list=merchTransactionsMapper.getOnlineDetail(transDataDTO);
        BizMerchTransactions voAmout=merchTransactionsMapper.getOnlineTransDetailCount(transDataDTO);
        BigDecimal amount=new BigDecimal("0.00");
        for(BizMerchTransactions vo:list){
            amount=amount.add(vo.getTransAmount());
        }
        ajaxResult.put("data",list);
        ajaxResult.put("amount",voAmout.getTransAmount());
        ajaxResult.put("count",voAmout.getCount());
        return ajaxResult;
    }


    @Override
    public Long selectAndInsertIdForClosure(String pos_sn, String amnount, String host_date) {
        return merchTransactionsMapper.selectAndInsertIdForClosure(pos_sn, amnount, host_date);
    }

    @Override
    public Date selectLastTransData(String posCode) {
        return merchTransactionsMapper.selectLastTransData(posCode);
    }

    @Override
    public BigDecimal getTransAmount(String merchantNo,String activeTime, String expireDate) {
        return merchTransactionsMapper.getTransAmount(merchantNo,activeTime,expireDate);
    }


}
